package com.gurun.codes.business.curtain;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;

import com.gurun.base.DebounceObservableTransformer;
import com.gurun.base.utils.ToastManager;
import com.gurun.codes.R;
import com.gurun.codes.base.BaseAppCompatActivity;
import com.gurun.codes.databinding.ActivityCommonBinding;
import com.gurun.codes.databinding.ContentCurtainBinding;
import com.gurun.codes.views.foldview.OnFoldListener;
import com.gurun.model.bean.ApiResult;
import com.jakewharton.rxbinding2.view.RxView;

import io.reactivex.functions.Consumer;

/**
 * 智能窗帘
 */
public class CurtainActivity extends BaseAppCompatActivity implements CurtainActivityContract.CurtainActivityView {
    private static final String ARG_DEVICE_ID = "device_id";
    private ActivityCommonBinding mBinding;
    private ContentCurtainBinding mContentBinding;
    private CurtainActivityContract.CurtainActivityViewPresenter mPresenter;
    private ProgressDialog mDialog;
    private long mDeviceId = 0;
    private int mCurrentProgress = 0;

    public static void startActivity(Context context, long deviceId) {
        Intent intent = new Intent(context, CurtainActivity.class);
        intent.putExtra(ARG_DEVICE_ID, deviceId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_common);
        mPresenter = new CurtainActivityContract.CurtainActivityViewPresenter(this);
        mPresenter.bind(this);
        initView();
        initDatas();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    @Override
    protected void initView() {
        mBinding.rlRoot.setBackgroundResource(R.mipmap.bg_curtain);
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        mContentBinding = DataBindingUtil.inflate(layoutInflater, R.layout.content_curtain, mBinding.llContent, true);
        mContentBinding.tvTitle.setText(R.string.curtain_title);
        mContentBinding.seekbar.setMax(100);
        mContentBinding.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                mCurrentProgress = i;
                float factor = i / 100f;
                setFactor(factor, false);
                //TODO 由于遥控器滑动监听不到onStopTrackingTouch,所以写在这里，尝试看看还有没有其它办法
                mPresenter.controlDevice(mDeviceId, null, mCurrentProgress, null, null);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
//                mPresenter.controlDevice(mDeviceId, null, mCurrentProgress, null, null);
            }

        });

        initFoldingView();
    }

    @Override
    protected void initDatas() {
        mDeviceId = getIntent().getLongExtra(ARG_DEVICE_ID, 0);

    }


    @Override
    protected void initEvent() {
        RxView.clicks(mContentBinding.ivOpen)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.controlDevice(mDeviceId, 1, null, null, null);
                    }
                });
        RxView.clicks(mContentBinding.ivStop)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.controlDevice(mDeviceId, 2, null, null, null);
                    }
                });
        RxView.clicks(mContentBinding.ivClose)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.controlDevice(mDeviceId, 0, null, null, null);
                    }
                });
    }

    @Override
    public void onLoading() {
//        if (mDialog == null) {
//            mDialog = new ProgressDialog(mContext);
//            mDialog.setMessage(getString(R.string.common_loading));
//        }
//        mDialog.show();
    }

    @Override
    public void onLoaded(ApiResult datas,Integer command) {
        if (command != null) {
            if (command == 0) {
                animateFoldClose();
            } else if (command == 1) {
                animateFoldOpen();
            }
        }
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(mContext, msg);
    }

    @Override
    public void onComplete() {
//        if (mDialog != null && mDialog.isShowing()) {
//            mDialog.dismiss();
//        }
    }

    //窗帘动画部分====================================
    private int mNumberOfFolds = 10;

    private void initFoldingView() {
        mContentBinding.foldviewLeft.setBackgroundResource(R.color.transparent);
        mContentBinding.foldviewLeft.setFoldListener(mOnFoldListenerLeft);
        mContentBinding.foldviewLeft.setNumberOfFolds(mNumberOfFolds);
        mContentBinding.foldviewLeft.setAnchorFactor(0);

        mContentBinding.foldviewRight.setBackgroundResource(R.color.transparent);
        mContentBinding.foldviewRight.setFoldListener(mOnFoldListenerRight);
        mContentBinding.foldviewRight.setNumberOfFolds(mNumberOfFolds);
        mContentBinding.foldviewRight.setAnchorFactor(1);
    }

    private OnFoldListener mOnFoldListenerLeft =
            new OnFoldListener() {
                @Override
                public void onStartFold() {
                    setSepiaLayer(mContentBinding.foldviewLeft.getChildAt(0), true);
                }

                @Override
                public void onEndFold() {
                    setSepiaLayer(mContentBinding.foldviewLeft.getChildAt(0), false);
                }
            };

    private OnFoldListener mOnFoldListenerRight =
            new OnFoldListener() {
                @Override
                public void onStartFold() {
                    setSepiaLayer(mContentBinding.foldviewRight.getChildAt(0), true);
                }

                @Override
                public void onEndFold() {
                    setSepiaLayer(mContentBinding.foldviewRight.getChildAt(0), false);
                }
            };

    private void setSepiaLayer(View view, boolean isSepiaLayerOn) {
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (isSepiaLayerOn) {
                view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            } else {
            }
        }
    }

    private void setFactor(float factor, boolean needSetSeekBarProgress) {
        if (factor < 0f) {
            factor = 0f;
        }
        if (factor > 1f) {
            factor = 1f;
        }
        if (needSetSeekBarProgress) {
            mContentBinding.seekbar.setProgress((int) (factor * 100));
        }
        if (factor >= 0.9f) {
            factor = 0.9f;
        }
        mContentBinding.foldviewLeft.setFoldFactor(factor);
        mContentBinding.foldviewRight.setFoldFactor(factor);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            float progress = (float) msg.obj;
            setFactor(progress, true);
        }
    };

    public void animateFoldOpen() {
        Message message = new Message();
        message.what = 1;
        message.obj = 1f;
        mHandler.sendMessage(message);
    }

    public void animateFoldClose() {
        Message message = new Message();
        message.what = 1;
        message.obj = 0f;
        mHandler.sendMessage(message);
    }
}
